import ROSLIB from 'roslib';
import { SENSOR_TOPICS } from '@/constants/ros';

export function createSensorService(ros, handlers) {
  const { onTemperature, onHumidity, onBattery, addLog } = handlers || {};
  const topics = {};

  // 统一的话题创建和订阅函数
  const createAndSubscribe = (topicName, messageType, callback, topicKey) => {
    const topic = new ROSLIB.Topic({
      ros,
      name: topicName,
      messageType
    });
    topic.subscribe(callback);
    topics[topicKey] = topic;
    return topic;
  };

  const subscribeAll = () => {
    // 使用统一函数创建话题
    createAndSubscribe(
      SENSOR_TOPICS.temperature,
      'std_msgs/msg/Float32',
      (msg) => onTemperature && onTemperature(msg?.data),
      'temperature'
    );

    createAndSubscribe(
      SENSOR_TOPICS.humidity,
      'std_msgs/msg/Float32',
      (msg) => onHumidity && onHumidity(msg?.data),
      'humidity'
    );

    createAndSubscribe(
      SENSOR_TOPICS.battery,
      'std_msgs/msg/Float32',
      (msg) => onBattery && onBattery(Number(msg?.data)),
      'battery'
    );

    addLog && addLog('传感器话题订阅已创建', 'success');
  };

  // 统一的取消订阅函数
  const safeUnsubscribe = (topicKey, topicName) => {
    try {
      if (topics[topicKey]) {
        topics[topicKey].unsubscribe();
        topics[topicKey] = null;
      }
    } catch (e) {
      addLog && addLog(`${topicName}话题取消订阅失败: ${e?.message || e}`, 'warning');
    }
  };

  const unsubscribeAll = () => {
    safeUnsubscribe('temperature', '温度');
    safeUnsubscribe('humidity', '湿度');
    safeUnsubscribe('battery', '电量');
  };

  return { subscribeAll, unsubscribeAll };
}


